<template>
  <div class="trans_box container">
    <div class="trans_header row">
      <!-- 切换翻译方向 -->
      <div class="tab_box col-6">
        <div class="trans_tab">
          <div class="trans_item">
            <!-- <span v-if="transState == 0" ref="left_text">中文</span>
            <span v-else ref="left_text">蒙文</span> -->

            <el-select v-model="transFrom" placeholder="请选择" @change="changeTransFrom">
              <el-option
                v-for="item in transOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div class="trans_icon_box">
            <img class="full" src="../assets/img/icon-trans.svg" alt="">
          </div>

          <div class="trans_item">
            <!-- <span v-if="transState == 0" ref="right_text">蒙文</span>
            <span v-else ref="right_text">中文</span> -->

            <el-select v-model="transTo" placeholder="请选择" @change="changeTransTo">
              <el-option
                v-for="item in transOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
    </div>

    <div class="trans_main row">
      <!-- 原文视图 -->
      <div class="left_box bgc_f7f7f7 p_5">
        <div 
          class="source_text pt_5" 
          contenteditable="true" 
          :class="{ vertical : transFrom == '蒙文' }" 
          ref="sourceText">
        </div>

        <!-- 清空按钮 -->
        <div class="clear_btn_box" v-if="sourceText" @click="clearText()">
          <img class="full" src="../assets/img/icon-clear.svg" alt="">
        </div>

        <div class="count_box">{{ sourceCount || 0 }} / 500</div>
      </div>

      <!-- 译文视图 -->
      <div class="right_box bgc_f7f7f7 p_10">
        <div class="trans_text" id="transText" :class="{ vertical : transTo == '蒙文' }" ref="transText">
          <span v-if="isShowLoading && transTo == '中文'">{{ transLoadingText.zh }}</span>
          <span v-if="isShowLoading && transTo == '蒙文'">{{ transLoadingText.mon }}</span>
          <span v-if="isShowLoading && transTo == '西里尔文'">{{ transLoadingText.cy }}</span>

          <span v-show="!isShowLoading">{{ transText || '' }}</span>
        </div>

        <div class="code_copy w_230 h_35">
          <!-- 复制 -->
          <div class="copy h_30 flex_row ph_13" @click="copy()">
            <div class="copy_icon">
              <img src="../assets/img/icon-copy.svg" alt="" >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Spinner from 'vue-simple-spinner'
  import { transC2M, transM2C, transC2K, transM2K } from '@/config/api'

  export default {
    name: 'Trans',
    components: { Spinner },
    props: {
      lang: ''
    },
    data() {
      return {
        transState: 0,    // 0: 中 -> 蒙   1: 蒙 -> 中

        timer: null,
        isShowLoading: false,
        
        transLoadingText: {
          zh: '翻译中...',
          mon: 'ᠣᠷᠴᠢᠭᠤᠯᠵᠤ ᠪᠠᠢᠨ᠎ᠠ ····',
          cy: 'Орчуулгын дунд...'
        },

        sourceText: '',
        sourceCount: 0,
        transText: '',

        transOptions: [
          { value: '中文', label: '中文' },
          { value: '蒙文', label: '蒙文' },
          { value: '西里尔文', label: '西里尔文' },
        ],

        transFrom: '中文',
        transTo: '蒙文'
      }
    },

    mounted() {
      this.$refs.sourceText.addEventListener('input', () => {
        let sourceText = this.$refs.sourceText.innerText
        this.inputSourceText(sourceText)
      })
    },

    methods: {
      // 改变翻译状态
      // changeTransState() {
      //   this.transState == 0 ? this.transState = 1 : this.transState = 0

      //   this.$refs.left_text.classList.add('left_animate')
      //   this.$refs.right_text.classList.add('right_animate')

      //   setTimeout(() => {
      //     this.$refs.left_text.classList.remove('left_animate')
      //     this.$refs.right_text.classList.remove('right_animate')
      //   }, 1200)

      //   this.clearText();
      // },

      changeTransFrom(val) {
        // console.log('transFrom : ', val);

        // if (val == '西里尔文') {
        //   this.$message.info('翻译西里尔文功能正在开发！')
        // }
        this.clearText();
      },

      changeTransTo(val) {
        // console.log('transTo : ', val);
        if (val !== this.transFrom) {
          this.trans(this.sourceText)
        } else if (val == this.transFrom) {
          this.transText = this.sourceText
        }

        // this.clearText();
      },

      // 清空原文 译文
      clearText() {
        this.$refs.sourceText.innerText = ''
        this.sourceText = ''
        this.sourceCount = 0

        this.transText = ''
      },

      // 监听原文输入
      inputSourceText(val) {
        var mo = /[\uE264-\uE34F]/;

        if (mo.test(val)) {
          // console.log(this.keyword)
          this.$message({
            message: '只允许转换标准编码蒙文',
            type: "warning",
          });

          this.$refs.sourceText.innerText = ''
          this.sourceText = ''
          this.sourceCount = 0
        }

        this.sourceText = val ? val : ''

        // 判断原文是否清空
        if (!val) {
          this.sourceCount = 0
          this.transText = ''
          clearTimeout(this.timer)
          return true
        }

        clearTimeout(this.timer)
				
        if (val.trim()) {
          this.timer = setTimeout(() => {
            // 计算原文蒙文字数
            if (this.transFrom == '蒙文') {
              this.computedMonTextLength(val)
            } else if (this.transFrom == '西里尔文') {
              this.computedCyTextLength(val)
            } else {
              // 计算中文
              this.sourceCount = val.length
            }

            this.trans(val)
          }, 1500)
        }
      },

      // 计算原文蒙文字数
      computedMonTextLength(val) { 
        let arr = []

        // 将 内容中的 标点符号 替换为 " "
        let str = val.replace(/[|\《|\》|\·|\(|\)|\︔|\᠄|\᠂|\<|\᠃|\︖]/g, "");
        // 将 内容 转换为 数组 ， 每一个 蒙文字 是一个 元素

        for (let i of str) {
          if (i === " ") {
            arr = str.split(" ")
          }
        }

        if (arr.length == 0 && str.length !== 0) {
          this.sourceCount = 1
          return false
        } else {
          // 删除数组中的 " "
          arr = arr.filter(item => {
            // return item !== ""
            return item.length !== 0
          })
          // 获取字数
          this.sourceCount = arr.length
        }
      },

      // 计算原文西里尔文字数
      computedCyTextLength(val) { 
        let arr = []

        // 将 内容中的 标点符号 替换为 " "   ( 西里尔文 字符 )
        let str = val.replace(/[|\,|\.|\?]/g, "");

        // 将 内容 转换为 数组 ， 每一个 西里尔文字 是一个 元素
        for (let i of str) {
          if (i === " ") {
            arr = str.split(" ")
          }
        }

        if (arr.length == 0 && str.length !== 0) {
          this.sourceCount = 1
          return false
        } else {
          // 删除数组中的 " "
          arr = arr.filter(item => {
            // return item !== ""
            return item.length !== 0
          })
          // 获取字数
          this.sourceCount = arr.length
        }
      },

      // 翻译
      async trans(text) {
        try {
          this.isShowLoading = true

          let params = {original_sentence: text}
          let res = null
          if (this.transFrom == '中文' && this.transTo == '蒙文') {
            res = await transC2M(params)
          } else if (this.transFrom == '蒙文' && this.transTo == '中文') {
            res = await transM2C(params)
          } else if (this.transFrom == '中文' && this.transTo == '西里尔文') {
            res = await transC2K(params)
          } else if (this.transFrom == '西里尔文' && this.transTo == '蒙文') {
            let params = {
              "US": "FangZhengShuBan",
              "PW": "1234567890",
              "ST": "CYRILLIC_TO_MONGOL",
              "LN": [text]
            }
            res = await transM2K(params)
          } 
          
          console.log('翻译返回 : ', res);

          // 返回 翻译 结果
          if (this.transFrom == '西里尔文' && this.transTo == '蒙文') {
            this.transText = res.LN[0]
          } else {
            this.transText = res.data.translate_sentence
          }

          this.isShowLoading = false
        } catch (err) {
          this.isShowLoading = false
        }
      },

      // 清空 原文、译文
      clearText() {
        this.$refs.sourceText.innerText = ''
        this.sourceText = ''
        this.sourceCount = 0

        this.transText = ''
        this.isShowLoading = false
      },

      // 复制译文
      copy() {
        if (this.transText) {
          this.copyText(this.transText)

          // navigator.clipboard.writeText(this.transText).then(() => {
          //   this.$message.success('复制成功！')
          // })
        } else {
          this.$message.info('暂无可复制内容！')
        }  
      },

      // 赋值 内容
      copyText(val) {
        if (navigator.clipboard && window.isSecureContext) {

          navigator.clipboard.writeText(this.transText).then(() => {
            this.$message.success('复制成功！')
          })
        } else {
          // 创建text area
          const textArea = document.createElement('textarea')
          textArea.value = val
          // 使text area不在viewport，同时设置不可见
          document.body.appendChild(textArea)
          textArea.focus()
          textArea.select()
          this.$message.success('复制成功')
          return new Promise((res, rej) => {
            // 执行复制命令并移除文本框
            document.execCommand('copy') ? res() : rej()
            textArea.remove()
          })
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .mon { 
    padding: 0 5px;
    line-height: 50px;
    writing-mode: vertical-lr; 
    font-family: mn; 
    -webkit-text-orientation: sideways-right;
    font-size: 16px; 
    padding-bottom: 10px !important;
  } 
  .vertical {
    writing-mode: vertical-lr;
    font-family: 'mn';
    -webkit-text-orientation: sideways-right;
    font-size: 22px;
  }

  .trans_box {
    width: 100%;
    height: calc(100% - 160px);
    // border: 1px solid #f00;
    padding-top: 1.2%;
    // position: absolute;
    // top: 50%;
    // left: 50%;
    // transform: translate(-50%, -50%);
    // overflow-y: auto;

    .trans_header {
      width: 100%;
      position: relative;

      .tab_box {
        width: 100%;
        border-radius: 8px;
        background-color: #f7f7f7;

        .trans_tab {
          width: 25%;
          height: 60px;
          overflow: hidden;
          display: flex;
          flex-direction: row;
          justify-content: space-around;
          align-items: center;

          .trans_item {
            width: 120px;
            text-align: center;
            color: #888;
          }
        
          .trans_icon_box {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            border: 1px solid #3372e2;
            background-color: #3372e2;
            position: relative;
            
            img { width: 85%; height: 85%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -48%); }
          }
        }
      }  
    }
  
    .trans_main {
      width: 100%;
      height: 70%;
      overflow: hidden;
      margin-top: 20px;
      // border: 1px solid #fff;

      .left_box {
        width: 48.5%;
        height: 100%;
        float: left;
        // border: 1px solid #999;
        border-radius: 10px;
        position: relative;

        .source_text {
          width: calc(100% - 50px);
          height: 90%;
          overflow: auto;
          resize:none;
          border: none;
          outline: none;
          color: #000;
          position: absolute;
          top: 5px;
          left: 10px;
        }

        .mn_ocr_loading_box {
          width: 100%;
          height: 100%;
          position: relative;

          .loading_box {
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }

        .clear_btn_box {
          width: 40px;
          height: 40px;
          background-color: #dcdfe6;
          border-radius: 50%;
          position: absolute;
          top: 5px;
          right: 5px;
        }
        .clear_btn_box:hover { 
          cursor: pointer; 
          background-color: #fff; 
          animation-name: animate1;
          animation-duration: 0.5s;
        }

        @keyframes animate1 {
          from {background-color: #232323;}
          to {background-color: #fff;}
        }

        .count_box {
          position: absolute;
          bottom: 15px;
          left: 15px;
          color: #888;
        }

        .voice_img {
          position: absolute;
          bottom: 15px;
          right: 15px;
          background-color: #161616;
          border-radius: 7px;
          .speech_recognition {
            .speech_icon:hover { cursor: pointer; }
          }
    
          .upload_img {
            position: absolute;
            right:15px;
            top: 2px;
            .img_icon:hover { cursor: pointer; }
          }
        }
      }
      .right_box {
        width: 48.5%;
        height: 100%;
        float: right;
        margin-left: 3%;
        // border: 1px solid #999;
        border-radius: 10px;
        position: relative;

        .trans_text {
          width: 100%;
          height: 100%;
          overflow: auto;
        }

        .code_copy {
          position: absolute;
          bottom: 10px;
          right: 15px;
          overflow: hidden;

          .code {
            width: 55%; 
            border-radius: 7px; 
            float: left; 
          }
          .copy { 
            width: 20%; 
            border-radius: 7px; 
            float: right; 
            background-color: #dcdfe6;
            position: relative;

            .copy_icon {
              width: 20px;
              height: 20px;
              position: absolute;
              top: 39%;
              left: 50%;
              transform: translate(-50%, -50%);

              img { width: 100%; height: 100%; }
            } 
          }
          .copy:hover { cursor: pointer; }
        }
      }
    }
  }

  .trans_box::-webkit-scrollbar {
    width: 0px;
    height: 100%;
    background-color: #f5f5f5;
  }

  .trans_box::-webkit-scrollbar-thumb {                 // 表示纵向滚动块
    border-radius: 0px;
  }

  @media screen and (min-width: 1800px) {

  }
  @media screen and (min-width: 1600px) and (max-width: 1800px) {
  }
  @media screen and (min-width: 1400px) and (max-width: 1599px) {
  }
  @media screen and (min-width: 1200px) and (max-width: 1399px) {    
  
  }
  @media screen and (min-width: 992px) and (max-width: 1199px) {
   
  }
  @media screen and (min-width: 768px) and (max-width: 991px) {

  }
  @media screen and (max-width: 767px) {
    .trans_box{ height :calc(100vh - 110px); }
  }

  @media screen and (min-width: 992px) {
    .trans_item, .trans_item_cy { display: block; }
  }
  @media screen and (max-width: 991px) {
    .trans_box { height :calc(100vh - 110px); margin-top: 6% !important; }
    .trans_main { height: calc(100% - 160px) !important; margin-top: 2.8% !important; }
    .row { margin-left: 0 !important; }
    .trans_item, .trans_item_cy { display: none; }
    .left_box, .right_box { width: 100% !important; height: 48% !important; margin: 0 auto; }
    .right_box { margin: 10px 0 0 0  !important; }

    .vertical { font-size: 18px !important; }
  }
</style>

